package org.example.admin.controller;

import org.example.admin.annotation.OperationLog;
import org.example.admin.exception.BizException;
import org.example.admin.exception.ControllerException;
import org.example.admin.service.NotifyService;
import org.example.admin.utils.StringUtils;
import org.example.entity.Notify;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


import java.io.*;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping("/notify")
public class NotifyController {

    private NotifyService notifyService;

    /**需要注意消息的存放路径*/
    @Value("${notifyContentLocation}")
    private String notifyContentPath;


    NotifyController(NotifyService notifyService){this.notifyService = notifyService;}


    @OperationLog("查看系统消息")
    @GetMapping("/systemMsg/{id}")
    public Object getMsgByUserId(@PathVariable("id") Integer id){
        Notify notify = null;

        try{
            notify = notifyService.getMsgById(id);
            System.out.println(notify);
        }catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            System.out.println(notify);
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }

        return  notify;
    }

    @OperationLog("查看历史消息")
    @GetMapping("/getAllMsg")
    public Object getAllMsgByUId(){
        List<Notify> list = null;
        try{
            list = notifyService.getAllMsg();
            System.out.println(list);
        }catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }


        return list;
    }

    @OperationLog("查看未读消息列表")
    @GetMapping("/getUnreadMsgList/{uId}")
    public Object getUnreadMsgListByUId(@PathVariable("uId") Integer uId){
        List<Notify> list = null;
        try{
            list = notifyService.getUnreadMsgListByUId(uId);
            System.out.println(list);
        }catch (BizException e) {
            throw e;
        } catch (Exception ex) {
            throw new ControllerException("控制层异常: " + ex.getMessage());
        }


        return list;
    }


    /**
     *前端需传入Notify对应所有属性
     * */
    @OperationLog("发布新的消息")
    @PostMapping("/insertNotify")
    public Object insertNotify(Notify notify){
        HashMap<String,Object> map = new HashMap<>();
        System.out.println("输出notify的值："+notify);

        //将前端得到的文本内容 转化成html文件。
        /*
        String words = notify.getnPath();
        uploadContent(words);
        */

        notify.setNCreateTime(new Date());
        notify.setNUpdateTime(new Date());
        try{
            notifyService.insertNotify(notify);
            map.put("code",1);
            map.put("msg","success");
        }catch (BizException e){
            throw e;
        }catch (Exception ex){
            throw new ControllerException("控制层异常："+ex.getMessage());
        }

        return map;
    }

    @OperationLog("删除消息")
    @DeleteMapping("/delete/{id}")
    public Object deleteNotifyById(@PathVariable("id") Integer id){
        HashMap<String, Object> map = new HashMap<>();
        try{
            notifyService.deleteNotifyById(id);
            map.put("code",1);
            map.put("msg","success");
        }catch (BizException e){
            throw e;
        }catch (Exception ex){
            throw new ControllerException("控制层异常："+ex.getMessage());
        }
        return map;
    }

    //需要留意登录的uId与发布消息的uId是否相同。
    @OperationLog("更新消息内容")
    @PutMapping()
    public Object updateNotifyById(Notify notify){
        HashMap<String, Object> map = new HashMap<>();
        try{
            notifyService.updateNotify(notify);
            map.put("code",1);
            map.put("msg","success");
        }catch (BizException e){
            throw e;
        }catch (Exception ex){
            throw new ControllerException("控制层异常："+ex.getMessage());
        }
        return map;
    }


    /**
     *  保存
     * */
    @OperationLog("保存输出的富文本内容")
    @PostMapping("/upload")
    public Object uploadContent(String words){
        Map<String, Object> map = new HashMap<>();
        //随机生成文件名。
        String newFileName = System.nanoTime() + StringUtils.generateRandomString(10)+".html";
        try{
            String content = URLDecoder.decode
                    (URLDecoder.decode(words,"UTF-8"),"UTF-8");
            System.out.println("查看乱码问题1："+content);
            String fileName = writeWord(content, newFileName);
            map.put("code",1);
            map.put("msg","success");
            map.put("fileName",fileName);
        }catch (BizException e){
            throw e;
        }catch (Exception ex){
            throw new ControllerException("控制层异常："+ex.getMessage());
        }

        return map;
    }

    //写入文件内容，可能有错。
    //乱码已解决。
    private String writeWord(String content,String fileName) {
        try {
            //path ->文件名。
            System.out.println("查看乱码问题2"+content);
            FileOutputStream fos = new FileOutputStream
                    (URLDecoder.decode(notifyContentPath+fileName, "UTF-8"));
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter
                    (fos,"UTF-8");
            PrintWriter printWriter = new
                    PrintWriter(outputStreamWriter);
            printWriter.write(content);
            printWriter.flush();
        } catch (BizException e){
            throw e;
        } catch(IOException ioException){
            throw new ControllerException("控制层写入异常："+ioException.getMessage());
        }

        return fileName;
    }
    /**
     *  编辑富文本，接收notifyId，在数据库查询，获取文件名nPath，然后加上路径，进行读取内容，将所得内容传回前端。
     * */

    @OperationLog("编辑富文本内容")
    @PostMapping("/edit/{id}")
    public Object editNotifyById(@PathVariable("id") Integer id){
        Notify notify = null;
        String fileName = null;
        HashMap<String, Object> map = new HashMap<>();
        try{
            notify = notifyService.getMsgById(id);
            fileName = notify.getNPath();
            //获取的内容
            String content = readWord(fileName);

            map.put("code",1);
            map.put("msg","success");
            map.put("title",notify.getNTitle());
            map.put("content",content);
        }catch (BizException e){
            throw e;
        }catch (Exception ex){
            throw new ControllerException("控制层异常："+ex.getMessage());
        }
        return map;
    }

    /**读取文件内容
     *
     * 编辑可用
     * */
    private String readWord(String fileName){
        try (
                FileInputStream  fileInputStream = new FileInputStream(URLDecoder.decode(notifyContentPath+fileName, "UTF-8"));
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
                BufferedReader br = new BufferedReader(inputStreamReader);
        ){
            String line = null;
            StringBuffer sBuffer = new StringBuffer();
            while((line = br.readLine())!=null){
                sBuffer.append(line);
            }
            return sBuffer.toString();
        } catch (BizException e){
            throw e;
        } catch(IOException ioException){
            throw new ControllerException(ioException.getMessage());
        }
    }
}

